package com.gljx.web.controller.back.power;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.gljx.constant.Constant;
import com.gljx.util.CommonUtil;
import com.gljx.web.Entity.Menu;
import com.gljx.web.service.MenuService;

import sun.misc.BASE64Decoder;

@Controller
@RequestMapping("/menu")
public class MenuAction {

	private  Logger logger = Logger.getLogger(getClass());
	
	@Autowired
	private MenuService menuService;
	
	/**
	 * 操作页
	* @author LiXiang  @date 2017年11月1日 下午4:52:46
	 */
	@RequestMapping("/look.action")
    public ModelAndView look() {
		ModelAndView mav=new ModelAndView();
		mav.setViewName("/backManage/power/menu_list");
		return mav;
	}
	/**
	 * 查询
	* @param id
	* @return
	* @author LiXiang  @date 2017年12月6日 下午3:40:01
	 */
	@RequestMapping("/alllist.action")
	@ResponseBody
    public List<Menu> alllist(String id) {
		List<Menu> menus= menuService.findAllBIMenu(Constant.Project_ID,id);
		return menus;
	}
	
	/**
	 * 获取菜单详情
	* @author LiXiang  @date 2017年11月1日 下午4:00:21
	 */
	@RequestMapping("/menudata.action")
	@ResponseBody
    public Map <String,Object > userdata(String id) {
		Map <String,Object > dataMap = new HashMap<String, Object>();
		dataMap.put("menu", menuService.selectByPrimaryKey(Integer.valueOf(id)));
		return dataMap;
	}
	/**
	 * 获取父菜单
	* @return
	* @author LiXiang  @date 2017年11月1日 下午3:04:32
	 */
	@RequestMapping("/PmenuList.action")
	@ResponseBody
	public List<Menu> PmenuList() {
		return menuService.allSysMenu("sys");
	}
	
	/**
	 * 插入
	* @author LiXiang  @date 2017年11月1日 下午4:59:20
	 * @throws IOException
	 */
	@RequiresPermissions("/menu/add.action")
	@RequestMapping("/add.action")
	@ResponseBody
    public Map <String,Object > add(Menu menu,String img,HttpServletRequest request) {
		this.imgSave(menu,img,request);
		Map <String,Object > dataMap = new HashMap<String, Object>();
	    dataMap.put("success",  menuService.insertSelective(menu));
		
		return dataMap;
	}
	
	/**
	 * 修改
	* @author LiXiang  @date 2017年11月1日 下午4:59:28
	 */
	@RequiresPermissions("/menu/update.action")
	@RequestMapping("/update.action")
	@ResponseBody
	//@RequiresRoles("admin_role")
    public Map <String,Object > update(Menu menu,String img,HttpServletRequest request){
		this.imgSave(menu,img,request);
		Map <String,Object > dataMap = new HashMap<String, Object>();
		dataMap.put("success",  menuService.updateByPrimaryKeySelective(menu));
		return dataMap;
	}
    	
	/**
	 * 批量停用、启用
	* @author LiXiang  @date 2017年11月1日 下午4:59:38
	 */
	@RequiresPermissions("/menu/setdelete.action")
	@RequestMapping("/setdelete.action")
	@ResponseBody
    public Map <String,Object > setdelete(String ids,String isDelete){
		Map <String,Object > dataMap = new HashMap<String, Object>();
		try {
			dataMap.put("success",menuService.updateMenuDelete(ids, isDelete));
		} catch (Exception e) {
			dataMap.put("erroe","");
			logger.error("#角色操作失败#---停用启用"+e);
		}
		return dataMap;
	}
	
	private Menu imgSave(Menu menu,String img,HttpServletRequest request){
		if(img != null && !"".equals(img)){
			String path=request.getServletContext().getRealPath(Constant.upload_IMG)+File.separatorChar;
			String [] imgall = img.split(",");
	        img = imgall[1];
	        String imgType = "."+imgall[0].split("\\/")[1].split(";")[0];
			String uuid=UUID.randomUUID().toString()+imgType;
			String fileName = path + uuid; 
			OutputStream imageStream = null;
			
			try {
				 BASE64Decoder decoder = new BASE64Decoder();
		         // Base64解码      
		         byte[] imageByte = null;
		         
		         imageByte = decoder.decodeBuffer(img);      
		         for (int i = 0; i < imageByte.length; ++i) { 
		             if (imageByte[i] < 0) {// 调整异常数据      
		                 imageByte[i] += 256;      
		             }
		         }

				String imgurl = File.separatorChar + Constant.UrlAfter + Constant.upload_IMG + File.separatorChar;
				// 生成文件
		         File imageFile = new File(fileName);
		         imageFile.createNewFile();
		         if(!imageFile.exists()){
		            imageFile.createNewFile();
		         }
		         imageStream = new FileOutputStream(imageFile);
		         imageStream.write(imageByte);
		         imageStream.flush();
		         menu.setImgUrl(imgurl+uuid);
			} catch (IOException e) {
				logger.error("#菜单图片==>>>>>>上传失败<<<<<====#"+e);
			} finally {
				 //关闭资源  
	            if(imageStream!= null){//检查资源是否为null  
	                 try {  
	                	 imageStream.close();  
	                 }catch (IOException e2 ) {  
	                	 logger.error("#菜单图片==>>>>>>上传IO关闭失败<<<<<====#"+e2);
	                      e2.printStackTrace();  
	                 }  
	            }  
			}
		     
		}
		return menu;
	}
}
